package com.daxia.bumall.util;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import com.daxia.bumall.common.Logs;
import com.daxia.bumall.common.SmsSendType;

public class SmsService {
    /**
     * 
     * @param 短信通客户接口测试
     * @param sendsmsaddress
     * @return
     * 
     */
    //public String commandID = "3";
    public String username = "ougong";
    public String password = "Hp13527999090";
    public String serviceURL = "http://api.smsbao.com/sms";
    public static String adminMobile = "15074921644";
    //public static String adminMobile = "13527999090";
    
    public static String connectURL(String commString, String sendsmsaddress) {
    	 BufferedReader reader = null;
         String result = null;
         StringBuffer sbf = new StringBuffer();
         sendsmsaddress = sendsmsaddress + "?" + commString;
         try {
             URL url = new URL(sendsmsaddress);
             HttpURLConnection connection = (HttpURLConnection) url.openConnection();
             connection.setRequestMethod("GET");
             connection.connect();
             InputStream is = connection.getInputStream();
             reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
             String strRead = reader.readLine();
             if (strRead != null) {
                 sbf.append(strRead);
                 while ((strRead = reader.readLine()) != null) {
                     sbf.append("\n");
                     sbf.append(strRead);
                 }
             }
             reader.close();
             result = sbf.toString();
         } catch (Exception e) {
             e.printStackTrace();
         }
         return result;
    }

    public String sendSms(String mobile, String content) {
    	if (DevUtils.isLocal() || DevUtils.isTestServer()) {
    		return "local";
    	}
    	 StringBuffer httpArg = new StringBuffer();
         httpArg.append("u=").append(username).append("&");
         httpArg.append("p=").append(md5(password)).append("&");
         httpArg.append("m=").append(mobile).append("&");
         httpArg.append("c=").append(encodeUrlString(content, "UTF-8"));
         String result = connectURL(httpArg.toString(), serviceURL);
         return result;
    }

    private String md5(String plainText) {
        StringBuffer buf = null;
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte b[] = md.digest();
            int i;
            buf = new StringBuffer("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0)
                    i += 256;
                if (i < 16)
                    buf.append("0");
                buf.append(Integer.toHexString(i));
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return buf.toString();
    }
 
    private String encodeUrlString(String str, String charset) {
        String strret = null;
        if (str == null)
            return str;
        try {
            strret = java.net.URLEncoder.encode(str, charset);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return strret;
    }
    
    /**
     * 发送指定类型的模板内容
     * @param mobile    手机号码
     * @param smsType   发送类型
     * @param map       传入模板参数，如：{"code","112233"},模板如：这里：{code}
     * @throws Exception
     */
    public static void sendWithTemplate(String mobile,Integer smsType,Map<String, Object> map) throws Exception {
    	if (DevUtils.isLocal() || DevUtils.isTestServer()) {
    		return;
    	}
    	SmsSendType sendType = SmsSendType.getByValue(smsType);
    	if(sendType == null) {
    		throw new RuntimeException("没有找到该短信模板内容");
    	} else {
    		String content = "";   //短信发送内容
    		String template = sendType.getTemplate();
    		Iterator<String> iter = map.keySet().iterator();   //遍历map，将所有的参数放进去
    		while(iter.hasNext()) {
    			String key = iter.next();
    			String matchKey = "{"+key+"}";
    			Object value = map.get(key);
    			if(template.indexOf(matchKey) > -1) {
    				template = template.replace(matchKey, value.toString());
    			}
    		}
    		content = template;
    		Logs.COMMON.debug("电话:"+mobile+"，短信内容："+content);
    		send(mobile, content);
    	}
    }
    
    public static void send(String mobile, String content) {
    	if (DevUtils.isLocal() || DevUtils.isTestServer()) {
    		return;
    	}
        //String mobile = "18508440628";
        // String content = "@";
        SmsService tt = new SmsService();
        String res = tt.sendSms(mobile, content);
        // 设置返回值
        Logs.COMMON.debug(res + ", mobile: " + mobile);
    }
    
    public static void main(String[] args) throws Exception {
        //send("13874918923", "hi");
    	Map<String, Object> map = new HashMap<String, Object>();
    	map.put("code", "这是测试的...");
    	sendWithTemplate("18910311849", SmsSendType.CompanyRegister.getValue(), map);
    }

}
